package cn.sixmillions.yuqueblog.service.impl;

import cn.hutool.http.HttpRequest;
import cn.sixmillions.yuqueblog.config.YuQueProperties;
import cn.sixmillions.yuqueblog.entity.Repo;
import cn.sixmillions.yuqueblog.entity.Toc;
import cn.sixmillions.yuqueblog.service.IRepoService;
import cn.sixmillions.yuqueblog.utils.RedisUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static cn.sixmillions.yuqueblog.common.constant.YuQueConstant.*;

/**
 * @description: 知识库接口实现
 * @author: sixmillions
 * @since: 2021/12/12
 **/
@Service
@Slf4j
public class RepoServiceImpl implements IRepoService {

    @Autowired
    private YuQueProperties conf;

    @Override
    public List<Repo> getRepoList(String login) {
        String cacheKey = String.format(REPOS_CACHE_KEY, login);
        String reposCache = RedisUtil.StringOps.get(cacheKey);
        if (StringUtils.isNotBlank(reposCache)) {
            //从缓存获取
            return JSON.parseArray(reposCache, Repo.class);
        }
        // 请求语雀API
        String requestUrl = String.format(REPO_URL, login);
        String reponseRes = HttpRequest.get(requestUrl).header(AUTH_HEADER, conf.getToken()).execute().body();
        String repos = JSON.parseObject(reponseRes).getString("data");
        RedisUtil.StringOps.set(cacheKey, repos);
        return JSON.parseArray(repos, Repo.class);
    }

    @Override
    public List<Toc> getToc(String namespace) {
        String cacheKey = String.format(REPO_TOC_CACHE_KEY, namespace);
        String tocCache = RedisUtil.StringOps.get(cacheKey);
        if (StringUtils.isNotBlank(tocCache)) {
            //从缓存获取
            return JSON.parseArray(tocCache, Toc.class);
        }
        // 请求语雀API
        String requestUrl = String.format(REPO_TOC_URL, namespace);
        String reponseRes = HttpRequest.get(requestUrl).header(AUTH_HEADER, conf.getToken()).execute().body();
        String toc = JSON.parseObject(reponseRes).getString("data");
        RedisUtil.StringOps.set(cacheKey, toc);
        return JSON.parseArray(toc, Toc.class);
    }

}
